#!/bin/bash

# x11vnc UTF-8剪贴板测试启动脚本
# 快速启动x11vnc并监控UTF-8剪贴板调试日志

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 项目路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
X11VNC_BIN="$SCRIPT_DIR/result/bin/x11vnc"
LOG_FILE="/tmp/x11vnc_utf8_test.log"
PID_FILE="/tmp/x11vnc_utf8_test.pid"

print_info "=== x11vnc UTF-8剪贴板测试启动 ==="

# 检查二进制文件
if [ ! -f "$X11VNC_BIN" ]; then
    print_error "找不到x11vnc二进制文件: $X11VNC_BIN"
    exit 1
fi

# 检查是否已经在运行
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        print_warning "x11vnc已经在运行 (PID: $PID)"
        print_info "如需重启，请先运行: $0 stop"
        exit 1
    else
        print_info "清理过期的PID文件"
        rm -f "$PID_FILE"
    fi
fi

# 设置DISPLAY
if [ -z "$DISPLAY" ]; then
    export DISPLAY=:0
    print_info "设置DISPLAY=$DISPLAY"
fi

# 检查X服务器
if ! xset q > /dev/null 2>&1; then
    print_error "无法连接到X服务器 (DISPLAY=$DISPLAY)"
    print_info "请确保X服务器正在运行"
    exit 1
fi

# 启动x11vnc
print_info "启动x11vnc服务器..."
print_info "二进制文件: $X11VNC_BIN"
print_info "日志文件: $LOG_FILE"
print_info "监听端口: 5900"

# 清理旧日志
rm -f "$LOG_FILE"

# 启动x11vnc (后台运行)
nohup "$X11VNC_BIN" \
    -display "$DISPLAY" \
    -rfbport 5900 \
    -forever \
    -shared \
    -o "$LOG_FILE" \
    -quiet \
    > /dev/null 2>&1 &

# 保存PID
echo $! > "$PID_FILE"

# 等待启动
sleep 3

# 检查是否启动成功
if ps -p $(cat "$PID_FILE") > /dev/null 2>&1; then
    print_success "✅ x11vnc启动成功 (PID: $(cat "$PID_FILE"))"
else
    print_error "❌ x11vnc启动失败"
    print_info "请检查日志文件: $LOG_FILE"
    exit 1
fi

# 检查端口监听
if netstat -ln | grep -q ":5900.*LISTEN"; then
    print_success "✅ 端口5900正在监听"
else
    print_warning "⚠️  端口5900未监听，可能还在启动中"
fi

print_info ""
print_info "=== 连接信息 ==="
print_info "VNC地址: $(hostname):5900"
print_info "或者: $(hostname -I | awk '{print $1}'):5900"
print_info ""
print_info "=== 监控命令 ==="
print_info "查看所有日志:"
echo "   tail -f $LOG_FILE"
print_info ""
print_info "查看剪贴板调试日志:"
echo "   tail -f $LOG_FILE | grep CLIPBOARD_DEBUG"
print_info ""
print_info "查看UTF-8相关日志:"
echo "   tail -f $LOG_FILE | grep -i utf8"
print_info ""
print_info "=== 测试步骤 ==="
print_info "1. 使用VNC客户端连接到上述地址"
print_info "2. 在VNC客户端中复制以下测试文本:"
echo "   - 中文: 你好世界"
echo "   - 特殊字符: café naïve résumé"
echo "   - 表情符号: 😊🎉"
print_info "3. 观察终端中的调试输出"
print_info ""
print_info "=== 停止服务 ==="
print_info "停止x11vnc: $0 stop"
print_info "或者: kill \$(cat $PID_FILE)"

# 可选：自动开始监控日志
read -p "是否开始监控剪贴板调试日志? [y/N]: " monitor
if [[ $monitor =~ ^[Yy]$ ]]; then
    print_info "开始监控剪贴板调试日志 (按Ctrl+C停止)..."
    sleep 2
    tail -f "$LOG_FILE" | grep --line-buffered "CLIPBOARD_DEBUG\|UTF8\|utf8"
fi

print_success "启动完成！"
